lib = Dir('lib')
build = Dir('build')
src = Dir('src')
inc = Dir('include')
bin = Dir('bin')

prefix = Dir(ARGUMENTS.get('prefix', '.'))
prefix_lib = prefix.Dir('lib')
prefix_inc = prefix.Dir('include')
prefix_bin = prefix.Dir('bin')

import os
cpath = os.environ.get('CPATH', "")
ld_library_path = os.environ.get('LD_LIBRARY_PATH', "")
cpp_paths = [cp for cp in cpath.split(':')]+[inc, prefix_inc]
lib_paths = [lp for lp in ld_library_path.split(':')]+[lib, prefix_lib]

ccflags = ['-Wall', '-Werror', '-ansi']

if 'debug' in COMMAND_LINE_TARGETS:
	ccflags += ['-g']
else:
	ccflags += ['-DBOOST_DISABLE_ASSERTS', '-DNDEBUG']

BuildDir(build, src, duplicate=0)

sources = """
crl.cpp				flat_tables.cpp			vi.cpp					rmax.cpp
environment.cpp		sparse_sampling.cpp  	uct.cpp					uctdata.cpp
ps.cpp	  			factor_learner.cpp		hash_tables.cpp			rtdp.cpp
ram.cpp
""".split()
headers = """
crl/crl.hpp         crl/flat_tables.hpp  	crl/uct.hpp				crl/uctdata.hpp		
crl/rmax.hpp 		crl/environment.hpp		crl/sparse_sampling.hpp	crl/vi.hpp
crl/ps.hpp          crl/common.hpp			crl/util.hpp			crl/rtdp.hpp
crl/types.hpp	 	crl/factor_learner.hpp	crl/hash_tables.hpp		crl/ram.hpp
crl/tables.hpp
""".split()

build_sources = [build.File(source) for source in sources]
test_sources = [build.File('test.cpp')]

env = Environment(tools = ["default", "tools"], toolpath = '.',
                  CPPPATH=cpp_paths, CCFLAGS=ccflags, LIBPATH=lib_paths)


shared_lib_suffix = ".so"
if os.uname()[0] == "Darwin":
	shared_lib_suffix = ".dylib"
	env.Append(SHLINKFLAGS='-undefined dynamic_lookup')
	
config = Configure(env)
config.CheckCXXHeader('cpputil.hpp')
config.CheckCXXHeader('boost/shared_ptr.hpp')
env = config.Finish()

lib_targets = []
bin_targets = []

libcrl = env.SharedLibrary(lib.File('libcrl'+shared_lib_suffix), build_sources)
lib_targets += [libcrl]

test = env.Program(bin.Entry('test'), test_sources, LIBS=['crl'])
bin_targets += [test]

if prefix != Dir('.'):
	for header in headers:
		env.Alias('install', env.InstallPerm(prefix_inc.Dir('crl'), inc.Entry(header), 0644))
	env.Alias('install', env.InstallPerm(prefix_inc, inc.Entry('cpputil.hpp'), 0644))
	env.Alias('install', env.InstallPerm(prefix_lib, lib_targets, 0644))
	env.Alias('install', env.InstallPerm(prefix_bin, bin_targets, 0755))

for target in lib_targets+bin_targets:
	Default(target)
	env.Alias('debug', target)

dist_files = [File(x) for x in """
COPYING COPYING.LESSER SConstruct tools.py
""".split()]
dist_files += [inc.Entry(header) for header in headers]
dist_files += [src.Entry(build_source) for build_source in build_sources] 
dist_files += [src.Entry(test_source) for test_source in test_sources] 

env.Alias('dist', env.DistTar('libcrl.tar.gz', dist_files))
	
